const getTextEle = (el, searchEle = 'span') => {
  const { children } = el;
  if (children.length > 0 && el.querySelector('.el-tooltip')) {
    return el;
  }
  if (children.length > 0) {
    return getTextEle(el.querySelector(searchEle));
  }
  return el;
};
const getSelfComp = binding => {
  const { parentComp } = binding.value;
  const tooltipVm = parentComp.$refs.panelLabelOverflowTooltip;
  return tooltipVm;
};
const bindFun = (el, binding) => {
  const self = getSelfComp(binding);
  self.parentComp = binding.value.parentComp;

  el.onmouseover = e => {
    const { target } = e;

    // 帮助信息图标
    const { className } = target;
    if (className === 'el-icon-info-filled') {
      self.isShow = false;
      return;
    }

    const labelEle = target.classList.contains('el-form-item__label') ? target : target.closest('.el-form-item__label');
    if (!labelEle) {
      self.isShow = false;
      return;
    }
    const textEle = getTextEle(labelEle);
    if (!textEle) {
      self.isShow = false;
      return;
    }

    const text = textEle.innerText; // 浮窗文字
    self.html = text;
    self.isShow = true;
    self.x = e.clientX;
    self.y = e.clientY;
    document.body.appendChild(self.$refs.overflowTip); // 移动到body层，防止被el-dialog弹窗遮挡
  };
  el.onmouseleave = e => {
    self.isShow = false;
    self.html = '';
    self.$el.appendChild(self.$refs.overflowTip); // 移动到本来位置，防止销毁前dom残留
  };
};

if (!window.visualComp.directives['panel-label-overflow-tooltip']) {
  window.visualComp.directives.push('panel-label-overflow-tooltip');
  window.xVueWeb.app.directive('panel-label-overflow-tooltip', {
    mounted: bindFun,
    updated: bindFun,
    unmounted: el => {
      el.onmouseenter = null;
      el.onmousemove = null;
      el.onmouseleave = null;
    },
  });
}
